<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="项目名称" prop="projectId">
        <el-select 
          v-model="queryParams.projectId" 
          placeholder="请选择项目" 
          clearable 
          filterable 
          :filter-method="filterProjects"
          @change="handleProjectChange"
          size="small"
        >
          <el-option
            v-for="item in projectOptions"
            :key="item.projectId"
            :label="item.projectName"
            :value="item.projectId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="房屋名称" prop="houseId">
        <el-select v-model="queryParams.houseId" placeholder="请选择房屋名称" clearable size="small">
          <el-option
            v-for="house in houseOptions"
            :key="house.houseId"
            :label="house.houseName"
            :value="house.houseId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <!-- 目录树 -->
      <el-col :span="5" :xs="24">
        <div class="head-container tree-container">
          <el-input
            v-model="folderName"
            placeholder="请输入目录名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 10px"
          />
          <el-tree
            :data="folderTree"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
            @node-contextmenu="handleRightClick"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>
                <img v-if="data.isHouse" src="@/assets/logo/logo.png" class="house-logo" />
                <img v-else-if="data.isProject" src="@/assets/images/project.png" class="house-logo" />
                <i v-else class="el-icon-folder" :class="{'el-icon-folder-opened': node.expanded}"></i>
                {{ node.label }}
              </span>
            </span>
          </el-tree>

          <!-- 右键菜单 -->
          <ul v-show="contextMenu.visible" :style="{left: contextMenu.x + 'px', top: contextMenu.y + 'px'}" class="context-menu">
            <li @click="handleContextMenuClick('add')">
              <i class="el-icon-plus"></i> 添加
            </li>
            <li @click="handleContextMenuClick('edit')">
              <i class="el-icon-edit"></i> 修改
            </li>
            <li @click="handleContextMenuClick('delete')">
              <i class="el-icon-delete"></i> 删除
            </li>
          </ul>
        </div>
      </el-col>

      <!-- 文档列表 -->
      <el-col :span="19" :xs="24">
        <el-row :gutter="10" class="mb8">
          <el-form :model="queryParams" :inline="true" class="top-search">
            <el-form-item label="文档名称" prop="docName">
              <el-input
                v-model="queryParams.docName"
                placeholder="请输入文档名称"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="文档类型" prop="docType">
              <el-select v-model="queryParams.docType" placeholder="请选择文档类型" clearable size="small">
                <el-option
                  v-for="dict in dict.type.doc_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
              >查询</el-button>
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['house:document:add']"
              >新增</el-button>
            </el-form-item>
          </el-form>
        </el-row>

        <el-table v-loading="loading" :data="documentList">
          <el-table-column label="文档名称" align="center" prop="docName" />
          <el-table-column label="文档类型" align="center" prop="docType">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.doc_type" :value="scope.row.docType"/>
            </template>
          </el-table-column>
          <el-table-column label="文件大小" align="center" prop="fileSize">
            <template slot-scope="scope">
              {{ formatFileSize(scope.row.fileSize) }}
            </template>
          </el-table-column>
          <el-table-column label="文件类型" align="center" prop="fileType" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handlePreview(scope.row, 'dialog')"
              >查看</el-button>
              <!-- <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handlePreview(scope.row, 'inline')"
              >直接预览</el-button> -->
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['house:document:remove']"
              >删除</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-download"
                @click="handleDownload(scope.row)"
              >下载</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 内联预览区域 -->
        <div v-if="inlinePreviewUrl" class="inline-preview-container">
          <div class="preview-header" :class="{ 'fullscreen': isFullscreen }">
            <span class="preview-title">{{ previewTitle }}</span>
            <el-button
              class="fullscreen-btn"
              :icon="isFullscreen ? 'el-icon-minus' : 'el-icon-full-screen'"
              :title="isFullscreen ? '退出全屏' : '全屏'"
              size="mini"
              circle
              @click="toggleFullScreen"
            />
          </div>
          <div class="preview-content" :class="{ 'is-fullscreen': isFullscreen }">
            <div v-if="previewLoading" class="preview-loading">
              <el-icon class="el-icon-loading"></el-icon>
              <p>正在加载文件，请稍候...</p>
            </div>
            <template v-else>
              <vue-office-pdf v-if="fileType === 'pdf'" :src="inlinePreviewUrl" />
              <vue-office-docx
                v-else-if="fileType === 'docx'" 
                :src="inlinePreviewUrl"
              />
              <vue-office-excel v-else-if="fileType === 'excel'" :src="inlinePreviewUrl" />
              <img v-else-if="fileType === 'image'" :src="inlinePreviewUrl" style="max-width: 100%;" />
              <dxf-viewer 
                v-else-if="fileType === 'dxf'" 
                :dxf-url="inlinePreviewUrl"
                :height="isFullscreen ? '100vh' : '600px'"
                :initial-zoom="2.5"
                :fit-margin="2"
                @loading-progress="onDxfLoadingProgress"
                @load-success="onDxfLoadSuccess"
                @load-error="onDxfLoadError"
              />
              <div v-else></div>
            </template>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 添加或修改文档对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文档类型" prop="docType">
          <el-select v-model="form.docType" placeholder="请选择文档类型">
            <el-option
              v-for="dict in dict.type.doc_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文档文件" prop="file">
          <el-upload
            class="upload-demo"
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            :file-list="fileList"
            :limit="1"
          >
            <el-button size="small" type="primary">选择文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传pdf/doc/docx/jpg/png/dwg/dxf文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改目录对话框 -->
    <el-dialog :title="folderTitle" :visible.sync="folderOpen" width="500px" append-to-body>
      <el-form ref="folderForm" :model="folderForm" :rules="folderRules" label-width="80px">
        <el-form-item label="目录名称" prop="folderName">
          <el-input v-model="folderForm.folderName" placeholder="请输入目录名称" />
        </el-form-item>
        <el-form-item label="排序号" prop="sortOrder">
          <el-input-number v-model="folderForm.sortOrder" :min="0" :max="999" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFolderForm">确 定</el-button>
        <el-button @click="cancelFolder">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 弹窗预览区域 -->
    <div v-if="previewOpen" class="popup-preview-wrapper">
      <div class="inline-preview-container" style="height: 85%; margin: 0;">
        <div class="preview-header" :class="{ 'fullscreen': isFullscreen }">
          <span class="preview-title">{{ previewTitle }}</span>
          <div>
            <el-button
              class="fullscreen-btn"
              :icon="isFullscreen ? 'el-icon-minus' : 'el-icon-full-screen'"
              :title="isFullscreen ? '退出全屏' : '全屏'"
              size="mini"
              circle
              @click="toggleFullScreen"
            />
            <el-button
              class="close-btn"
              icon="el-icon-close"
              title="关闭"
              size="mini"
              circle
              @click="previewOpen = false"
            />
          </div>
        </div>
        <div class="preview-content" :class="{ 'is-fullscreen': isFullscreen }">
          <div v-if="previewLoading" class="preview-loading">
            <el-icon class="el-icon-loading"></el-icon>
            <p>正在加载文件，请稍候...</p>
          </div>
          <template v-else>
            <vue-office-pdf v-if="fileType === 'pdf'" :src="previewUrl" />
            <vue-office-docx
              v-else-if="fileType === 'docx'" 
              :src="previewUrl"
            />
            <vue-office-excel v-else-if="fileType === 'excel'" :src="previewUrl" />
            <img v-else-if="fileType === 'image'" :src="previewUrl" style="max-width: 100%;" />
            <dxf-viewer 
              v-else-if="fileType === 'dxf'" 
              :dxf-url="previewUrl"
              :height="isFullscreen ? '100vh' : '100%'"
              :initial-zoom="2.0"
              :fit-margin="2"
              @loading-progress="onDxfLoadingProgress"
              @load-success="onDxfLoadSuccess"
              @load-error="onDxfLoadError"
            />
            <div v-else></div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import VueOfficeDocx from '@vue-office/docx'
import VueOfficePdf from '@vue-office/pdf'
import VueOfficeExcel from '@vue-office/excel'
import DxfViewer from '@/components/DxfViewer'
import {
  getFolderTree,
  addFolder,
  updateFolder,
  delFolder,
  listDocument,
  getDocument,
  uploadDocument,
  updateDocument,
  delDocument,
  exportDocument,
  getDocumentsByFolder,
  downloadDocument,
  previewDocument
} from "@/api/house/document";
import { listHouse } from "@/api/house/house";
import { listProjects } from "@/api/house/project";

export default {
  name: "Document",
  dicts: ['doc_type'],
  components: {
    'vue-office-docx': VueOfficeDocx,
    'vue-office-pdf': VueOfficePdf,
    'vue-office-excel': VueOfficeExcel,
    DxfViewer
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文档表格数据
      documentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 目录树数据
      folderTree: [],
      // 目录名称
      folderName: "",
      // 当前选中的目录ID
      currentFolderId: null,
      // 当前选中的房屋ID
      currentHouseId: null,
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        docName: null,
        docType: null,
        folderId: null,
        houseId: null,
        projectId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        docType: [
          { required: true, message: "文档类型不能为空", trigger: "change" }
        ]
      },
      // 目录表单标题
      folderTitle: "",
      // 目录表单显示状态
      folderOpen: false,
      // 目录表单数据
      folderForm: {},
      // 目录表单校验
      folderRules: {
        folderName: [
          { required: true, message: "目录名称不能为空", trigger: "blur" }
        ]
      },
      // 文件列表
      fileList: [],
      // 上传地址
      uploadUrl: process.env.VUE_APP_BASE_API + "/house/document/upload",
      // 树形控件配置选项
      defaultProps: {
        children: "children",
        label: "folderName"
      },
      // 房屋选项
      houseOptions: [],
      // 右键菜单相关数据
      contextMenu: {
        visible: false,
        x: 0,
        y: 0,
        currentNode: null
      },
      // 预览相关数据
      previewOpen: false,
      previewTitle: '',
      previewUrl: '',
      fileType: '',
      isFullscreen: false,  // 添加全屏状态控制
      inlinePreviewUrl: '', // 内联预览URL
      // 项目选项
      projectOptions: [],
      // 过滤后的项目选项
      filteredProjectOptions: [],
      previewLoading: false, // 添加预览加载状态
    };
  },
  created() {
    // 只获取项目列表
    listProjects().then(projectRes => {
      this.projectOptions = projectRes.rows;
      
      // 从路由参数中获取房屋ID
      const houseId = this.$route.params.houseId;
      if (houseId) {
        this.currentHouseId = parseInt(houseId);
        this.queryParams.houseId = this.currentHouseId;
        
        // 如果有房屋ID,则获取对应的房屋信息和项目信息
        listHouse({houseId: houseId}).then(houseRes => {
          if (houseRes.rows && houseRes.rows.length > 0) {
            const house = houseRes.rows[0];
            this.queryParams.projectId = house.projectId;
            // 获取该项目下的所有房屋
            listHouse({projectId: house.projectId}).then(response => {
              this.houseOptions = response.rows;
            });
          }
        });
        
        // 获取文档列表和目录树
        this.getList();
        this.getFolderTree();
      }
    });
  },
  mounted() {
    // 点击空白处隐藏右键菜单
    document.addEventListener('click', this.hideContextMenu);
  },
  beforeDestroy() {
    // 组件销毁前移除事件监听
    document.removeEventListener('click', this.hideContextMenu);
  },
  methods: {
    /** 获取房屋选项列表 */
    getHouseOptions() {
      return listHouse().then(response => {
        this.houseOptions = response.rows;
      });
    },
    /** 查询文档列表 */
    getList() {
      if (!this.queryParams.projectId && !this.queryParams.houseId) {
        this.loading = false;
        this.documentList = [];
        this.total = 0;
        return;
      }
      this.loading = true;
      this.queryParams.folderId = this.currentFolderId;
      listDocument(this.queryParams).then(response => {
        this.documentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询目录树 */
    getFolderTree() {
      const params = {};
      if (this.queryParams.projectId) {
        // 如果选择了项目，先获取项目下的所有房屋
        listHouse({ projectId: this.queryParams.projectId }).then(houseResponse => {
          const houses = houseResponse.rows;
          // 获取项目信息
          const project = this.projectOptions.find(p => p.projectId === this.queryParams.projectId);
          if (!project) {
            this.folderTree = [];
            return;
          }

          // 构建项目节点
          const projectNode = {
            id: 'project_' + project.projectId,
            folderName: project.projectName,
            children: [],
            isProject: true
          };

          // 如果选择了具体房屋，只显示该房屋
          if (this.queryParams.houseId) {
            const selectedHouse = houses.find(h => h.houseId === this.queryParams.houseId);
            if (selectedHouse) {
              const houseNode = {
                id: 'house_' + selectedHouse.houseId,
                folderName: selectedHouse.houseName,
                children: [],
                isHouse: true,
                houseId: selectedHouse.houseId
              };
              projectNode.children.push(houseNode);

              // 获取该房屋的文档目录
              params.houseId = selectedHouse.houseId;
              getFolderTree(params).then(response => {
                const folders = response.data || [];
                houseNode.children = this.convertToTree(folders);
                this.folderTree = [projectNode];
              }).catch(() => {
                this.folderTree = [projectNode];
              });
            }
          } else {
            // 显示项目下所有房屋
            houses.forEach(house => {
              const houseNode = {
                id: 'house_' + house.houseId,
                folderName: house.houseName,
                children: [],
                isHouse: true,
                houseId: house.houseId
              };
              projectNode.children.push(houseNode);
            });

            // 获取所有文档目录
            params.projectId = this.queryParams.projectId;
            getFolderTree(params).then(response => {
              const folders = response.data || [];
              
              // 将文档目录分配到对应的房屋节点下
              projectNode.children.forEach(houseNode => {
                const houseFolders = folders.filter(f => f.houseId === houseNode.houseId);
                houseNode.children = this.convertToTree(houseFolders);
              });

              this.folderTree = [projectNode];
            }).catch(() => {
              this.folderTree = [projectNode];
            });
          }
        });
      } else {
        this.folderTree = [];
      }
    },
    /** 将平铺的目录数据转换为树形结构 */
    convertToTree(list) {
      const map = {};
      const tree = [];
      
      // 先用map存储每个节点
      list.forEach(item => {
        map[item.id] = { ...item, children: [] };
      });
      
      // 构建树形结构
      list.forEach(item => {
        const node = map[item.id];
        if (item.parentId === 0) {
          // parentId为0的是根节点
          tree.push(node);
        } else {
          // 将当前节点添加到父节点的children中
          const parent = map[item.parentId];
          if (parent) {
            parent.children.push(node);
          }
        }
      });
      
      // 对每个层级按sortOrder排序
      const sortTree = (nodes) => {
        nodes.sort((a, b) => a.sortOrder - b.sortOrder);
        nodes.forEach(node => {
          if (node.children && node.children.length > 0) {
            sortTree(node.children);
          }
        });
        return nodes;
      };
      
      return sortTree(tree);
    },
    /** 转换文件大小 */
    formatFileSize(size) {
      if (size < 1024) {
        return size + 'B';
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(2) + 'KB';
      } else if (size < 1024 * 1024 * 1024) {
        return (size / (1024 * 1024)).toFixed(2) + 'MB';
      } else {
        return (size / (1024 * 1024 * 1024)).toFixed(2) + 'GB';
      }
    },
    // 文档类型字典翻译
    docTypeFormat(row, column) {
      return this.selectDictLabel(this.dict.type.doc_type, row.docType);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        houseId: this.currentHouseId,
        folderId: this.currentFolderId,
        docType: null,
        docName: null,
        docUrl: null,
        fileSize: null,
        fileType: null,
        status: 1,
        remark: null
      };
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.currentHouseId = this.queryParams.houseId;
      // 如果有房屋ID或项目ID，获取目录树
      if (this.currentHouseId || this.queryParams.projectId) {
        this.getFolderTree();
      } else {
        this.folderTree = [];
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.houseOptions = []; // 清空房屋列表
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      // 获取当前选中的树节点
      const node = this.$refs.tree.getCurrentNode();
      if (!node) {
        this.$modal.msgWarning("请先选择一个目录");
        return;
      }
      if (node.isProject) {
        this.$modal.msgWarning("不能在项目层级添加文档");
        return;
      }

      this.reset();
      // 如果是房屋节点，设置parentId为0
      if (node.isHouse) {
        this.form.parentId = 0;
        this.form.houseId = node.houseId;
      } else {
        this.form.parentId = node.id;
        this.form.houseId = node.houseId;
      }
      this.form.projectId = this.queryParams.projectId;
      this.open = true;
      this.title = "添加文档";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getDocument(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文档";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDocument(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if (this.fileList.length === 0) {
              this.$message.error('请选择要上传的文件');
              return;
            }
            // 创建 FormData 对象
            const formData = new FormData();
            // 添加文件
            formData.append('file', this.fileList[0].raw);
            // 添加其他表单数据
            Object.keys(this.form).forEach(key => {
              if (this.form[key] !== null && this.form[key] !== undefined) {
                if (key === 'expireDate' && this.form[key]) {
                  formData.append(key, this.parseTime(this.form[key], '{y}-{m}-{d}'));
                } else {
                  formData.append(key, this.form[key]);
                }
              }
            });

            uploadDocument(formData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error('上传失败:', error);
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除文档编号为"' + ids + '"的数据项？').then(function() {
        return delDocument(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('house/document/export', {
        ...this.queryParams
      }, `document_${new Date().getTime()}.xlsx`);
    },
    /** 文件上传之前的钩子 */
    beforeUpload(file) {
      const isValidType = [
        'application/pdf', 
        'application/msword', 
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 
        'image/jpeg', 
        'image/png',
        'application/acad',  // AutoCAD DWG/DXF
        'image/vnd.dwg',     // AutoCAD DWG/DXF
        'application/x-dwg', // AutoCAD DWG
        'application/x-dxf'  // AutoCAD DXF
      ].indexOf(file.type) !== -1 || file.name.toLowerCase().endsWith('.dwg') || file.name.toLowerCase().endsWith('.dxf');
      
      if (!isValidType) {
        this.$message.error('只能上传PDF/Word/JPG/PNG/DWG/DXF格式文件！');
        return false;
      }
      const isLt50M = file.size / 1024 / 1024 < 50;
      if (!isLt50M) {
        this.$message.error('文件大小不能超过 50MB!');
        return false;
      }
      return true;
    },
    /** 文件上传成功的钩子 */
    handleUploadSuccess(response, file, fileList) {
      this.form.docUrl = response.data;
      this.form.docName = file.name;
      this.form.fileSize = file.size;
      this.form.fileType = file.name.substring(file.name.lastIndexOf("."));
      this.$modal.msgSuccess("上传成功");
    },
    /** 文件上传失败的钩子 */
    handleUploadError() {
      this.$message.error("上传失败，请重试");
    },
    /** 树节点点击事件 */
    handleNodeClick(data) {
      // 如果点击的是项目节点或房屋节点，不执行任何操作
      if (data.isProject || data.isHouse) {
        return;
      }
      this.currentFolderId = data.id;
      this.getList();
    },
    /** 添加目录 */
    handleAddFolder(data) {
      // 如果是项目节点，不允许添加
      if (data.isProject) {
        this.$message.warning('不能在项目层级添加目录');
        return;
      }

      this.folderForm = {
        projectId: this.queryParams.projectId,
        houseId: data.isHouse ? data.houseId : data.houseId,
        parentId: data.isHouse ? 0 : data.id,
        folderName: '',
        sortOrder: 0
      };
      this.folderOpen = true;
      this.folderTitle = "添加目录";
    },
    /** 修改目录 */
    handleEditFolder(data) {
      // 如果是项目节点或房屋节点，不允许修改
      if (data.isProject || data.isHouse) {
        this.$message.warning('不能修改此层级的名称');
        return;
      }
      this.folderForm = Object.assign({}, data);
      this.folderOpen = true;
      this.folderTitle = "修改目录";
    },
    /** 删除目录 */
    handleDelFolder(data) {
      // 如果是项目节点或房屋节点，不允许删除
      if (data.isProject || data.isHouse) {
        this.$message.warning('不能删除此层级的目录');
        return;
      }
      this.$modal.confirm('是否确认删除名称为"' + data.folderName + '"的目录？').then(function() {
        return delFolder(data.id);
      }).then(() => {
        this.getFolderTree();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 提交目录表单 */
    submitFolderForm() {
      this.$refs["folderForm"].validate(valid => {
        if (valid) {
          if (this.folderForm.id != null) {
            updateFolder(this.folderForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.folderOpen = false;
              this.getFolderTree();
            });
          } else {
            addFolder(this.folderForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.folderOpen = false;
              this.getFolderTree();
            });
          }
        }
      });
    },
    /** 取消目录操作 */
    cancelFolder() {
      this.folderOpen = false;
      this.folderForm = {};
      this.resetForm("folderForm");
    },
    /** 过滤节点 */
    filterNode(value, data) {
      if (!value) return true;
      return data.folderName.indexOf(value) !== -1;
    },
    /** 处理右键点击事件 */
    handleRightClick(event, data, node, component) {
      event.preventDefault();
      this.contextMenu.visible = true;
      this.contextMenu.x = event.clientX;
      this.contextMenu.y = event.clientY;
      this.contextMenu.currentNode = data;
    },
    /** 处理右键菜单点击 */
    handleContextMenuClick(type) {
      const data = this.contextMenu.currentNode;
      if (!data) return;

      switch (type) {
        case 'add':
          this.handleAddFolder(data);
          break;
        case 'edit':
          this.handleEditFolder(data);
          break;
        case 'delete':
          this.handleDelFolder(data);
          break;
      }
      this.hideContextMenu();
    },
    /** 隐藏右键菜单 */
    hideContextMenu() {
      this.contextMenu.visible = false;
    },
    /** 文件选择变化时的处理 */
    handleFileChange(file, fileList) {
      this.fileList = fileList.slice(-1);
    },
    /** 下载按钮操作 */
    handleDownload(row) {
      downloadDocument(row.id).then(response => {
        // 创建 blob
        const blob = new Blob([response], {
          type: 'application/octet-stream'
        });
        // 创建下载链接
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = row.docName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      }).catch(err => {
        this.$modal.msgError("下载失败");
        console.error('下载失败:', err);
      });
    },
    /** 预览按钮操作 */
    handlePreview(row, type = 'dialog') {
      if (type === 'dialog') {
        this.previewOpen = true;
      }
      this.previewTitle = row.docName;
      this.previewUrl = '';
      this.inlinePreviewUrl = '';
      this.fileType = '';
      this.previewLoading = true; // 设置加载状态为true
      
      // 根据文件类型设置预览方式
      const fileType = row.fileType.toLowerCase();
      
      // 获取文件的实际URL
      previewDocument(row.id).then(response => {
        if (fileType === '.pdf') {
          this.fileType = 'pdf';
          const blob = new Blob([response], { type: 'application/pdf' });
          const url = window.URL.createObjectURL(blob);
          if (type === 'dialog') {
            this.previewUrl = url;
          } else {
            this.inlinePreviewUrl = url;
          }
        } else if (fileType === '.docx') {
          this.fileType = 'docx';
          const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
          const url = window.URL.createObjectURL(blob);
          if (type === 'dialog') {
            this.previewUrl = url;
          } else {
            this.inlinePreviewUrl = url;
          }
        } else if (['.xlsx', '.xls'].includes(fileType)) {
          this.fileType = 'excel';
          const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
          const url = window.URL.createObjectURL(blob);
          if (type === 'dialog') {
            this.previewUrl = url;
          } else {
            this.inlinePreviewUrl = url;
          }
        } else if (['.jpg', '.jpeg', '.png', '.gif'].includes(fileType)) {
          this.fileType = 'image';
          const mimeType = fileType === '.png' ? 'image/png' : 
                          fileType === '.gif' ? 'image/gif' : 'image/jpeg';
          const blob = new Blob([response], { type: mimeType });
          const url = window.URL.createObjectURL(blob);
          if (type === 'dialog') {
            this.previewUrl = url;
          } else {
            this.inlinePreviewUrl = url;
          }
        } else if (['.dwg', '.dxf'].includes(fileType)) {
          this.fileType = 'dxf';
          const blob = new Blob([response], { type: 'application/octet-stream' });
          const url = window.URL.createObjectURL(blob);
          console.log(url)
          if (type === 'dialog') {
            this.previewUrl = url;
          } else {
            this.inlinePreviewUrl = url;
          }
        } else {
          this.$modal.msgError("暂不支持该类型文件的预览");
          if (type === 'dialog') {
            this.previewOpen = false;
          }
          return;
        }
        this.previewLoading = false; // 加载完成后设置状态为false
      }).catch(err => {
        this.previewLoading = false; // 加载失败时也要设置状态为false
        this.$modal.msgError("预览失败");
        console.error('预览失败:', err);
        if (type === 'dialog') {
          this.previewOpen = false;
        }
      });
    },
    /** 切换全屏状态 */
    toggleFullScreen() {
      this.isFullscreen = !this.isFullscreen;
    },
    /** DXF文件加载进度处理 */
    onDxfLoadingProgress({ phase, processed, total }) {
      console.log(`DXF加载进度: ${phase}, ${processed}/${total}`)
    },

    /** DXF文件加载成功处理 */
    onDxfLoadSuccess() {
      //this.$message.success('DXF文件加载成功')
    },

    /** DXF文件加载失败处理 */
    onDxfLoadError(error) {
      console.error('DXF文件加载失败:', error)
      this.$message.error('DXF文件加载失败')
    },
    /** 项目选择框筛选方法 */
    filterProjects(query) {
      if (query) {
        const search = query.toLowerCase();
        this.filteredProjectOptions = this.projectOptions.filter(item => 
          item.projectName.toLowerCase().includes(search)
        );
      } else {
        this.filteredProjectOptions = this.projectOptions;
      }
    },
    /** 项目选择变化处理 */
    handleProjectChange(projectId) {
      this.queryParams.houseId = null;
      if (projectId) {
        // 根据项目ID获取对应的房屋列表
        listHouse({projectId: projectId}).then(response => {
          this.houseOptions = response.rows;
        });
      } else {
        // 重新获取所有房屋列表
        listHouse().then(response => {
          this.houseOptions = response.rows;
        });
      }
      // 清空当前选中的房屋和目录
      this.currentHouseId = null;
      this.currentFolderId = null;
      this.folderTree = [];
      this.handleQuery();
    },
  },
  watch: {
    folderName(val) {
      this.$refs.tree.filter(val);
    },
    'queryParams.houseId': {
      handler(newVal) {
        if (!newVal) {
          this.currentHouseId = null;
          this.currentFolderId = null;
          this.folderTree = [];
        }
      }
    }
  }
};
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.custom-tree-node i {
  margin-right: 5px;
  color: #909399;
}

.custom-tree-node i.el-icon-folder-opened {
  color: #409EFF;
}

/* 添加树节点选中样式 */
:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #f0f7ff !important;
  color: #409EFF;
}

/* 添加树节点悬停样式 */
:deep(.el-tree-node__content:hover) {
  background-color: #f5f7fa;
}

.context-menu {
  position: fixed;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  padding: 5px 0;
  margin: 0;
  z-index: 2000;
  list-style: none;
}

.context-menu li {
  margin: 0;
  padding: 7px 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.context-menu li:hover {
  background: #f5f7fa;
  color: #409EFF;
}

.context-menu li i {
  margin-right: 5px;
}

.fullscreen-btn {
  padding: 3px;
  margin-left: 8px;
  font-size: 12px;
}

.preview-container {
  height: 100%;
  overflow: auto;
}

.preview-container :deep(.docx-wrapper) {
  padding: 20px;
}

/* 内联预览容器样式 */
.inline-preview-container {
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.preview-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 15px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.preview-title {
  font-size: 14px;
  color: #606266;
}

.preview-content {
  padding: 20px;
  min-height: 400px;
  /* max-height: 600px; */
  overflow-y: auto;
}

.preview-content.is-fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2000;
  background: white;
  padding: 0;
  margin: 0;
  max-height: none;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.preview-content.is-fullscreen > * {
  flex: 1;
  height: 100%;
  width: 100%;
}

.preview-header.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 2001;
  background: white;
  border-bottom: 1px solid #ebeef5;
  box-shadow: 0 1px 4px rgba(0,0,0,0.08);
  padding: 8px 15px;
}

/* 全屏状态下的标题栏样式 */
.preview-content.is-fullscreen + .preview-header,
.preview-content.is-fullscreen ~ .preview-header {
  display: none;
}

.preview-content.is-fullscreen {
  padding-top: 45px;
  height: 100vh;
}

/* 预览对话框样式 */
:deep(.preview-dialog) {
  .el-dialog__header {
    padding: 0;
    height: 0;
  }
  
  .el-dialog__body {
    padding: 0;
  }
}

.close-btn {
  padding: 3px;
  margin-left: 8px;
  font-size: 12px;
}

/* 弹窗预览样式 */
.popup-preview-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 2000;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px;
}

.popup-preview-wrapper .inline-preview-container {
  width: 80%;
  max-width: 1200px;
  height: 90vh;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.popup-preview-wrapper .preview-content {
  flex: 1;
  overflow: auto;
  padding: 20px;
}

.popup-preview-wrapper .preview-content.is-fullscreen {
  padding-top: 45px;
  height: 100vh;
}

/* 目录树容器样式 */
.tree-container {
  background: #fff;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 10px;
  height: calc(100vh - 200px);
  overflow: auto;
}

.tree-container .el-input {
  margin-bottom: 10px;
}

.tree-container .el-tree {
  margin-top: 5px;
  border: none;
  background: transparent;
}

/* 顶部搜索区域样式 */
.top-search {
  :deep(.el-form-item) {
    margin-bottom: 0;
    margin-right: 8px;
  }

  :deep(.el-form-item__content) {
    width: auto;
  }

  :deep(.el-input),
  :deep(.el-select) {
    width: 200px;
  }
}

.house-logo {
  width: 16px;
  height: 16px;
  margin-right: 5px;
  vertical-align: middle;
}

.preview-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  
  .el-icon-loading {
    font-size: 32px;
    margin-bottom: 10px;
  }
  
  p {
    margin: 0;
    font-size: 14px;
  }
}
</style> 